package com.zl.cms.controller;


import com.zl.basic.CommonUtil.EnumUtil;
import com.zl.cms.auth.AuthClass;
import com.zl.cms.model.Role;
import com.zl.cms.model.RoleType;
import com.zl.cms.service.IRoleService;
import com.zl.cms.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.inject.Inject;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-1-27 Time: 下午3:55
 */
@RequestMapping("/admin/role")
@Controller
@AuthClass
public class RoleController {

  private IRoleService roleService;
  private IUserService userService;

  public IRoleService getRoleService() {
    return roleService;
  }

  @Inject
  public void setRoleService(IRoleService roleService) {
    this.roleService = roleService;
  }

  public IUserService getUserService() {
    return userService;
  }

  @Inject
  public void setUserService(IUserService userService) {
    this.userService = userService;
  }

  @RequestMapping("/roles")
  public String list(Model model) {
    model.addAttribute("roles", roleService.listRole());
    return "role/list";
  }

  @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  public String show(@PathVariable int id, Model model) {
    model.addAttribute(roleService.load(id));
    model.addAttribute("users", userService.listRoleUsers(id));
    return "role/show";
  }

  @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
  public String delete(@PathVariable int id) {
    roleService.delete(id);
    return "redirect:/admin/role/roles";
  }

  @RequestMapping(value = "/cleanusers/{id}")
  public String cleanusers(@PathVariable int id) {
    roleService.deleteRoleUsers(id);
    return "redirect:/admin/role/roles";
  }


  @RequestMapping(value = "/add", method = RequestMethod.GET)
  public String add(Model model) {
    model.addAttribute(new Role());
    model.addAttribute("types", EnumUtil.enum2Name(RoleType.class));
    return "role/add";
  }

  @RequestMapping(value = "/add", method = RequestMethod.POST)
  public String add(Role role) {
    roleService.add(role);
    return "redirect:/admin/role/roles";
  }

  @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
  public String update(@PathVariable int id, Model model) {
    model.addAttribute(roleService.load(id));
    model.addAttribute("types", EnumUtil.enum2Name(RoleType.class));
    return "role/update";
  }

  @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
  public String update(@PathVariable int id, Role role) {
    Role or = roleService.load(id);
    or.setName(role.getName());
    or.setRoleType(role.getRoleType());
    roleService.update(or);
    return "redirect:/admin/role/roles";

  }



}
